//
// Source code recreated from a .class file by IntelliJ IDEA
// (powered by FernFlower decompiler)
//

package com.lbank.spiderflow.core.executor.shape;

import groovy.lang.Binding;
import groovy.lang.GroovyClassLoader;
import groovy.lang.Script;
import java.io.IOException;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class GroovyScriptManager {

    private static final Logger LOGGER = LoggerFactory.getLogger(GroovyScriptManager.class);

    protected static Map<String, Class<?>> scriptMap = new ConcurrentHashMap<>();

    public static Class<?> getAndCachedScript(String script) {
        String scriptMd5 = Md5Util.encrypt(script);
        return scriptMap.computeIfAbsent(scriptMd5, (key) -> {
            Class<?> scriptClass = null;
            try (GroovyClassLoader groovyClassLoader = new GroovyClassLoader()) {
                scriptClass = groovyClassLoader.parseClass(script);
                LOGGER.info("Groovy类缓存数量：{}", scriptMap.size());
                return scriptClass;
            } catch (IOException e) {
                LOGGER.warn("Groovy类加载器资源释放异常：{}", e.getMessage(), e);
                return scriptClass;
            }
        });
    }

    public static Object run(Class<?> scriptClass, Binding binding) throws Exception {
        Script scriptInstance = (Script)scriptClass.getDeclaredConstructor().newInstance();
        scriptInstance.setBinding(binding);
        return scriptInstance.run();
    }
}
